package fragment;

import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.content.Context;
import android.widget.ImageView;
import android.widget.TextView;

import com.lanou.horo.myapplication.R;
import com.lanou.horo.myapplication.dbdao.PersonEntity;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import application.BasisApplication;
import dbdao.UserDBHepler;
import de.greenrobot.event.EventBus;
import tools.QQUtil;
import utils.texttools.RegexValidateUtil;
import utils.texttools.StringUtil;

/**
 * Created by dllo on 15/11/26.
 */

public class LoginFragment extends AbsBaseFragment implements View.OnClickListener, View.OnFocusChangeListener, TextWatcher {
    private TextView login_qq, login_weixin, login_weibo;
    private EditText loginName, loginPsw;
    private RadioButton rememberRadio;
    private Button login_btn, registered_btn;
    private TextView mUserInfo, titleForAllTv, nameSizeTv;
    private ImageView titleForAllBack, mUserLogo;
    private UserDBHepler hepler;
    public static QQAuth mQQAuth;
    private UserInfo mInfo;
    String name;
    String password;
    private Tencent mTencent;
    private final String APP_ID = "222222";// 测试时使用，真正发布的时候要换成自己的APP_ID
    public static String mAppid;
    private static Boolean showPassword = false;
    //    private CharSequence temp;//监听前的文本
//    private int editStart;//光标开始位置
//    private int editEnd;//光标结束位置
//    private final int charMaxNum = 15;
    private SharedPreferences sp;
    @Override
    protected int getLayoutView() {
        return R.layout.fragment_login;
    }

    @Override
    public void onStart() {

        final Context context = getContext();
        final Context ctxContext = context.getApplicationContext();
        mAppid = APP_ID;
        mQQAuth = QQAuth.createInstance(mAppid, ctxContext);
        mTencent = Tencent.createInstance(mAppid, getContext());
        super.onStart();
    }


    @Override
    protected void initView() {
        nameSizeTv = findView(R.id.nameSizeTv);
        titleForAllTv = findView(R.id.titleForAllTv);
        titleForAllBack = findView(R.id.titleForAllBack);
        registered_btn = findView(R.id.registered_btn);
        login_btn = findView(R.id.login_btn);
        loginName = findView(R.id.loginName);
        loginPsw = findView(R.id.loginPsw);
        login_qq = findView(R.id.login_qq);
        login_weixin = findView(R.id.login_weixin);
        login_weibo = findView(R.id.login_weibo);
        rememberRadio = findView(R.id.RememberRadio);
        sp = getContext().getSharedPreferences("userInfo",
                Context.MODE_WORLD_READABLE);
    }

    @Override
    protected void initData() {
        titleForAllTv.setText("登录");
        registered_btn.setOnClickListener(this);
        login_btn.setOnClickListener(this);
        loginName.setOnFocusChangeListener(this);
        loginName.addTextChangedListener(this);
        loginPsw.setOnFocusChangeListener(this);
        loginPsw.setOnClickListener(this);
        login_qq.setOnClickListener(this);
        login_weixin.setOnClickListener(this);
        login_weibo.setOnClickListener(this);
        hepler = UserDBHepler.getInstance();
        login_btn.setClickable(false);
        titleForAllBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });

        if (sp.getBoolean("ISCHCK", false)) {
            rememberRadio.setChecked(true);
            loginName.setText(sp.getString("USER_NAME", ""));
            loginPsw.setText(sp.getString("PASSWORD", ""));
        }
        rememberRadio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sp.edit().putBoolean("ISCHCK", true).commit();

                } else {
                    sp.edit().putBoolean("ISCHCK", false).commit();
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginPsw:
                showPassword();
                break;
            case R.id.login_qq:
                onClickLogin();
                break;
            case R.id.login_weixin:
                break;
            case R.id.login_weibo:
                break;
            case R.id.registered_btn:
                goToMenu(new RegisteredFragment());
                break;
            case R.id.login_btn:
                name = loginName.getText().toString();
                password = loginPsw.getText().toString();

                // 判断输入内容是否为空
                if (!StringUtil.isEmpty(password)) {
                    if (RegexValidateUtil.checkMobileNumber(name) || RegexValidateUtil.checkEmail(name)) {
                        PersonEntity usermsg = hepler.getUsermsgByPhoneNumber(name);
                        if (usermsg != null) {
                            if (name.equals(usermsg.getPhoneNumber())) {
                                if (password.equals(usermsg.getPassword())) {
                                    toastPrompt("登录成功");
                                    BasisApplication.setIsLogin(true);
                                    BasisApplication.setUser(usermsg);
                                    EventBus.getDefault().post(BasisApplication.isLogin());

                                    if (rememberRadio.isChecked()) {
                                        SharedPreferences.Editor editor = sp.edit();
                                        editor.putString("USER_NAME", name);
                                        editor.putString("PASSWORD", password);
                                        editor.commit();
                                    }
                                    goBack();
                                } else {
                                    toastWarning("密码不正确");
                                }
                            } else {
                                toastWarning("用户名不正确");
                            }
                        } else {
                            toastWarning("用户不存在");
                        }
                    } else {
                        toastWarning("用户名为邮箱或手机号");
                    }
                } else {
                    toastWarning("密码不能为空");
                }
                break;
        }
    }


    private  void showPassword(){
        if (showPassword) {//显示密码
            showPassword = !showPassword;
            loginPsw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            loginPsw.setSelection(loginPsw.getText().toString().length());
        } else {//隐藏密码
            showPassword = !showPassword;
            loginPsw.setTransformationMethod(PasswordTransformationMethod.getInstance());
            loginPsw.setSelection(loginPsw.getText().toString().length());
        }
    }
    //对登陆按钮的监听
    private void onClickLogin() {
        if (!mQQAuth.isSessionValid()) {
            IUiListener listener = new BaseUiListener() {
                @Override
                protected void doComplete(JSONObject values) {
                }
            };
            mQQAuth.login(getActivity(), "all", listener);
            mTencent.login(getActivity(), "all", listener);
        } else {
            mQQAuth.logout(getActivity());
        }
    }


    private class BaseUiListener implements IUiListener {


        public void onComplete(Object response) {
            //登录成功之后的跳转
            goBack();
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {

        }


        public void onError(UiError e) {
            QQUtil.toastMessage(getActivity(), "onError: " + e.errorDetail);
            QQUtil.dismissDialog();
        }

        public void onCancel() {
            QQUtil.toastMessage(getActivity(), "onCancel: ");
            QQUtil.dismissDialog();
        }
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.loginName:

                break;
            case R.id.loginPsw:

                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }


    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() > 0) {
//            login_btn.setEnabled(true); //使能控件，如果设置为false，该控件永远不会活动，不管设置为什么属性，都无效；
            login_btn.setClickable(true);//设置为true时，表明控件可以点击，如果为false，就不能点击；
            login_btn.setBackgroundResource(R.drawable.tab_login_btn);
        } else {
            login_btn.setClickable(false);
            login_btn.setBackgroundColor(0xFF9b9694);
        }

        if (RegexValidateUtil.checkEmail(s.toString()) || RegexValidateUtil.checkMobileNumber(s.toString())) {
            nameSizeTv.setText("格式正确");
        } else {
            nameSizeTv.setText("手机号或邮箱格式不正确");
        }

    }

}
